package com.zhangshanfeng.test;

import java.util.concurrent.locks.ReentrantLock;

/*
Lock锁

 */
public class Ticket implements Runnable {
    private static int ticket = 100;
    private static Object obj = new Object();
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            //  synchronized(obj){
            lock.lock();

            try {

                if (ticket == 0) {
                    break;
                } else {
                    Thread.sleep(50);
                }
                ticket--;
                System.out.println(Thread.currentThread().getName() + "正在出票还剩余" + ticket + "张");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {

                lock.unlock();//释放锁必须放在finally块中---（不然会等死）
            }





        }


    }
}

class TicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t = new Thread(ticket, "窗口1");
        Thread t2 = new Thread(ticket, "窗口2");
        Thread t3 = new Thread(ticket, "窗口3");
        t.start();
        t2.start();
        t3.start();


    }
}
